<template>
  <div v-loading="!form">
    <el-form
      v-if="form"
      ref="goodsForm"
      :model="form"
      :rules="rules"
      label-width="20%"
      label-suffix="："
      class="form-fixed"
      @submit.native.prevent
    >
      <el-form-item
        label="参观单位名称"
        prop="company_name"
        inline-message
        class="form-item--medium"
      >
        <el-input
          ref="formInput.company_name"
          v-model="form.company_name"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="参观联系人姓名"
        prop="contact"
        class="form-item--medium"
      >
        <el-input
          v-model="form.contact"
          maxlength="10"
        />
      </el-form-item>
      <el-form-item
        label="参观联系人手机号"
        prop="contact_mobile"
        class="form-item--medium"
      >
        <el-input
          v-model="form.contact_mobile"
          maxlength="11"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="公司对接部门"
        prop="waiter_department_id"
        class="form-item--medium"
      >
        <el-select
          v-model="form.waiter_department_id"
          clearable
          placeholder="请选择公司对接部门"
        >
          <el-option
            v-for="(item,index) in options.departments"
            :key="index"
            :label="item.name"
            :value="item.id"
            :disabled="item.disabled"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="公司对接人"
        prop="waiter_name"
        class="form-item--medium"
      >
        <el-input
          v-model="form.waiter_name"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item
        label="参观需求"
        prop="categorys"
      >
        <el-checkbox-group v-model="form.categorys">
          <el-checkbox
            v-for="item in categorys"
            :key="item.id"
            :label="item.id"
          >
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        label="场地需求"
        prop="room_id"
      >
        <el-radio-group v-model="form.room_id">
          <el-radio-button
            v-for="item in visitmodeRooms"
            :key="item.id"
            :label="item.id"
            :value="item.id"
            border
            :disabled="item.disabled"
          >
            <div>
              {{ item.name }}
            </div>
            <div class="text-muted mt-2 font-size-sm">
              {{ item.description }}
            </div>
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="参观日期"
        prop="date"
      >
        <el-date-picker
          v-model="form.date"
          type="date"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          placeholder="选择参观日期"
          @change="onChangeDate"
        />
      </el-form-item>
      <el-form-item
        label="参观时段"
        prop="stages"
      >
        <el-checkbox-group v-model="form.stages">
          <el-checkbox
            v-for="item in stages"
            :key="item.id"
            :label="item.id"
            :disabled="item.disabled"
          >
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <fixed-box>
        <el-form-item>
          <div>
            <el-button
              type="primary"
              @click="onSubmit"
            >提交保存</el-button>
          </div>
          <div>
            <slot name="steps" />
            <el-button @click="goBack">返回</el-button>
          </div>
        </el-form-item>
      </fixed-box>
    </el-form>
  </div>
</template>

<script>
import FixedBox from '@/layout/components/FixedBox'
export default {
  name: 'GoodsBaseForm',
  components: {
    FixedBox
  },
  inject: ['goBack'],
  props: {
    value: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      cascaderProps: { value: 'id', label: 'name', emitPath: true },
      rules: {
        company_name: [{ required: true, message: '请输入参观单位名称', trigger: 'blur' }],
        room_id: [{ required: true, message: '请选择场地需求', trigger: 'change' }],
        body: [
          {
            type: 'array',
            required: true,
            message: '请设置商品详情信息'
          }
        ],
        date: [
          {
            type: 'string',
            required: true,
            message: '请选择参观日期',
            trigger: 'change'
          }
        ],
        stages: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个时段',
            trigger: 'change'
          }
        ],
        categorys: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个参观需求',
            trigger: 'change'
          }
        ],
        contact: [{ required: true, message: '请填写活动形式', trigger: 'blur' }],
        contact_mobile: [{ required: true, message: '请填写活动形式', trigger: 'blur' }],
        waiter_department_id: [{ required: true, message: '请选择公司对接部门', trigger: 'blur' }],
        waiter_name: [{ required: true, message: '请填写公司对接人', trigger: 'blur' }]
      },
      form: null,
      options: null,
      safeAttributes: [],
      pickerOptions: {
        disabledDate: this.disabledDate
      }
    }
  },
  computed: {
    rooms() {
      return this.options.rooms.map(item => {
        return item
      })
    },
    stages() {
      return this.options.stages.map(item => {
        var idString = item.id
        console.log(item)
        if (item.disabled) {
          var index = this.form.stages.indexOf(idString)
          if (index !== -1) {
            this.form.stages.splice(index, 1)
          }
        }
        return item
      })
    },
    categorys() {
      return this.options.categorys.map(item => {
        return item
      })
    },
    visitmodeRooms() {
      var roomIds = this.rooms.map(item => {
        return item.id
      })
      var mins = roomIds
      var categorys = []
      if (this.form.categorys && this.form.categorys.length > 0) {
        for (var i = 0; i < this.form.categorys.length; i++) {
          var visitMode = this.categorys.find(mode => {
            return mode.id === this.form.categorys[i]
          })
          categorys.push(visitMode)
        }
      }
      for (i = 0; i < categorys.length; i++) {
        const { rooms } = categorys[i]
        mins = this.$utils.arrayDiff(mins, rooms)
      }
      return this.rooms.map(item => {
        var disabled = item.disabled
        if (!disabled && mins.indexOf(item.id) === -1) {
          disabled = true
        }
        if (disabled && this.form.room_id !== '' && this.form.room_id === item.id) {
          this.form.room_id = ''
        }
        return { ...item, disabled: disabled }
      })
    },
    dateStart() {
      const now = new Date()
      now.setDate(now.getDate() + 2)
      const date = this.$moment(now).format('yyyy-mm-dd')
      console.log(date)
      return date
    },
    dateEnd() {
      const now = new Date()
      now.setDate(now.getDate() + 60)
      const date = this.$moment(now).format('yyyy-mm-dd')
      console.log(date)
      return date
    },
    currentDate() {
      const now = new Date()
      now.setDate(now.getDate() + 2)
      return this.$moment(now).format('yyyy-mm-dd')
    }
  },
  mounted() {
    this.onLoad()
  },
  methods: {
    disabledDate(date) {
      var weekend = !(date.getDay() % 6)
      return weekend || this.$moment().isAfter(date, 'day') // 禁止选择今天以后的时间
    },
    onLoad() {
      this.$http.book.formConfig(this.value).then(res => {
        console.log('onLoadConfig', res.data)
        this.onMountData(res.data)
      })
    },
    onChangeDate(date) {
      console.log(date)
      this.form.date = date
      this.onCheckOnlineStage(date, this.id)
    },
    onCheckOnlineStage(date, bookId) {
      this.$http.book.checkBookStage(date, bookId).then(res => {
        const stages = res.data
        this.options.stages = stages
        console.log(this.options.stages)
      })
    },
    onMountData(data) {
      const { form, options, safeAttributes } = data
      this.form = { ...form }
      this.options = options
      this.safeAttributes = safeAttributes
    },
    onSubmit() {
      this.$refs.goodsForm.validate((valid, obj) => {
        if (valid) {
          this.submit()
        } else {
          let firstErrorElname = ''
          for (const i in obj) {
            firstErrorElname = `formInput.${i}`
            break
          }
          var dom = this.$refs[firstErrorElname]
          console.log(dom, this.$refs)
          if (dom) {
            dom.$refs.input && dom.$refs.input.focus()
            dom.$el.scrollIntoView({
              // 滚动到指定节点
              block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
              behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            })
          }
          console.log('error submit!!', this.form)
          return false
        }
      })
    },
    submit() {
      this.$http.book.update(this.form, this.value).then(res => {
        if (res.data) {
          this.$emit('saved', res.data)
        }
      })
    }
  }
}
</script>
